package com.app.config;

import com.app.common.BaseVo;
import com.app.common.ResultCode;
import com.app.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @autor xiaoyu.fang
 * @date 2018/12/8 22:51
 */
@Slf4j
@Component
@ControllerAdvice
public class ErrorHandler {

    /**
     * 业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleBindException(BusinessException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ex);
    }

    /**
     * 参数验证、绑定异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseVo handleValidateException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.ERR_CHECK_PARAM.getCode(),
                ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 控制层参数校验
     *
     * @param ex
     * @param req
     * @param res
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleAllException(Throwable ex, HttpServletRequest req, HttpServletResponse res) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.SERVICE_ERROR.getCode(),
                ResultCode.SERVICE_ERROR.getInfo());
    }

    /**
     * 绑定异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public BaseVo handleBindException(BindException ex) {
        log.error(ex.getMessage(), ex);
        return BaseVo.error(ResultCode.ERR_CHECK_PARAM.getCode(), ex.getFieldError()
                .getDefaultMessage());
    }
}
